package com.clouddong.exterapi.controller;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.clouddong.exterapi.po.ProbeListTablePo;
import com.clouddong.exterapi.po.ProbeXmlPingListJoinPo;
import com.clouddong.exterapi.service.ProbeClientServiceI;
import com.clouddong.exterapi.service.impl.ProbeClientServiceImpl;
import com.clouddong.exterapi.util.Tools;
import com.clouddong.exterapi.vo.ProbeListTableVo;

import net.sf.json.JSONObject;

/**
<blockquote>
<h1>客户接口的的控制器类</h1>
* @author lpr
* @version 1.0.0
* @date [2018年7月17日 下午1:23:25]
*/
@Controller
@RequestMapping(value="probeClientApi")
@CrossOrigin(origins="*")//解决跨域问题
public class ProbeClientController
{
	@Resource(name="probeClientServiceImpl")
	private ProbeClientServiceI probeClientServiceI;
	// 地市集合下的地市Ping码对应的key也就是[{ name: '大兴安岭地区', value: 0 }]中的value
	private final Object cityPingCodeKey = ProbeClientServiceImpl.CITY_PINGCODE_KEY;
	//private final int intervalTime=5;//间隔的单位秒
	//private final int overTime = 300;//超时的时间单位秒
	
	private final static Logger logger = LoggerFactory.getLogger(ProbeClientController.class);
	
	/**
	<blockquote>
	<h1>根据任务ID查询省份对应的Ping值</h1>
	* @version 1.0.0
	* @param task_id - 任务ID
	* @return
	 */
	@RequestMapping(value="getProvincePingQuery",method= {RequestMethod.POST},produces="application/json;charset=utf-8")
	@ResponseBody
	public JSONObject getClientPing(@RequestParam(name="task_id",required=false)String task_id)
	{
		System.out.println("-----------进入了getClientPing方法---------");
		JSONObject retJson=new JSONObject();//定义最终返回的JSON
		String[] verInfo=isAttributeLeg(task_id);
		if(!Boolean.parseBoolean(verInfo[0]))
		{//判断产数是否合法,不合法就返回对应的JSON
			retJson.put("status_code", 3);
			retJson.put("describe", verInfo[1]);
			return retJson;
		}
		if(true)
		{
		  try {
			/*Long indexTime=(long)0;//时间累加值
			Boolean result = false;//判断是否还需要循环
			while(!result)
			{//循环执行查询*/			
			  //获取list表下的所有数据
			List<ProbeListTablePo> listTableDataList=probeClientServiceI.getDataSourceIsOperQuery(new ProbeListTableVo());
			//判断list表下是否有数据
				if(listTableDataList.size()>0)
				{
				//获取数据源
				//PageInfo<ProbeJointTablePo> pageDataList= probeClientServiceI.getPageDataSourceIsClientTask(task_id, 1, 3);
				List<ProbeXmlPingListJoinPo> dataList=probeClientServiceI.getDataSourceIsClientPingMap(task_id);
				if(dataList.size()>0){
				//获取封装后的JSON数据
				Map<String, List<Map<String, Object>>> dataMap=probeClientServiceI.getFinalJsonIsClient(dataList);
				//判断并更改省份的Ping码
				dataMap=isProvincePingExi(dataMap,ProbeClientServiceImpl.getIsProPingJson(),probeClientServiceI.PRO_PINGCODE_KEY);
				//转化为JSON
				retJson=JSONObject.fromObject(dataMap);
				//result=true;
				}else{
					retJson.put("mssage", "wait for");
				}
			 	}else{
			 		//result=true;
			 		retJson.put("mssage", "无可用探针");
			 	}
				/*if(!result)
				{//判断是否需要线程睡眠
					indexTime+=intervalTime*1000;
					Thread.currentThread().sleep(intervalTime*1000);
				}
				if(indexTime>=overTime*1000)
				{//判断是否超时
					retJson.clear();
			 		retJson.put("mssage", "查询超时");
					break;
				}
			}*/
		  }catch (Exception e){
			e.printStackTrace();
		  } 
		}
		return retJson;
		
	}
	/** 
	<blockquote>
	<h1>根据自定义的规则拿地市的Ping码去判断省份的Ping码</h1>
	* @version 1.0.0
	* @param retJson 最终返回的没有经过判断的JSON
	* @return - JSON格式的经过判断加工的JSON
	 */
	private Map<String,List<Map<String,Object>>> isProvincePingExi(Map<String,List<Map<String,Object>>> retMap
			,Map<String, List<Map<String,Object>>> cityBasisJson,String provPingCodeKey)
	{
		Map<String,List<Map<String,Object>>> map=retMap;
		try {
		if(cityBasisJson.size()!=0||(cityBasisJson.size()!=map.size()))
		{
			//定义一个迭代器用来遍历retJson
			Iterator<String> keyIterator =map.keySet().iterator();
			List<Map<String,Object>> dataJsonAll;
			Map<String,Object> provMap;
            while(keyIterator.hasNext())
            {//遍历retJson的key
    			Integer index=0;//定义一个计数器，计算出现的次数
            	Integer proPingCode=0;
    			String key = keyIterator.next();//获得json的key
            	//获取该List<Object>的最后一位类型为List<JSONObject>的地市信息
    			dataJsonAll = map.get(key);
            	provMap=dataJsonAll.get(0);
            	for(int i=0,len=dataJsonAll.size();i<len;i++)
            	{
            	  if(new Integer(0).equals(Integer.parseInt(cityBasisJson.get(key).get(i).get(cityPingCodeKey).toString())))
            	  {
            		index++;
            	  }
            	}
            	if((index*1.0)>=dataJsonAll.size()/2.0)
            	{//判断当前Ping码出现的次数是否大于另一个Ping码出现的次数
            		proPingCode=0;//能Ping通
            	}else{
            		proPingCode=1;//Ping不通
				}
            	//逆向将修改完毕的元素放回
            	provMap.put(provPingCodeKey, proPingCode);
            	dataJsonAll.set(0, provMap);
            	map.put(key, dataJsonAll);
            }
		}
		}catch (Exception e) 
		{//捕获异常
			e.printStackTrace();
		}
		return map;
	}
	/**
	<blockquote>
	<h1>判断传入的属性是否合法</h1>
	* @version 1.0.0
	* @param obj - 传入的属性
	* @return String[]类型，0位为是否合法true或false，value为提示信息
	 */
	private String[] isAttributeLeg(Object obj)
	{
		String[] retStrAll=new String[]{"true",""};
		if(obj==null)
		{
			retStrAll[0]="false";
			retStrAll[1]="Can't be null";
			return retStrAll; 
		}
		if(!Tools.isNumber(obj.toString()))
		{
			retStrAll[0]="false";
			retStrAll[1]="Only for numbers";
			return retStrAll;
		}
		return retStrAll;
	}
	
}
